// 页面加载时获取数据
window.onload = function () {
    fetchMoney();
    fetchAllCards();
};

// 获取所有卡牌
function fetchAllCards() {
    fetch('/api/shop/available-cards')
        .then(response => response.json())
        .then(data => {
            const currentMoney = parseInt(document.getElementById('currentMoney').textContent);
            // 保存滑动条的位置
            const scrollPositions = {};
            Array.from(document.getElementsByClassName('card-scroll-container')).forEach(container => {
                scrollPositions[container.id] = container.scrollLeft;
            });

            // 清空现有卡牌
            document.getElementById('roleCards').innerHTML = '';
            document.getElementById('actionCards').innerHTML = '';
            document.getElementById('totalWeaponCards').innerHTML = '';
            document.getElementById('roleWeaponCards').innerHTML = '';

            // 分类并显示卡牌
            data.forEach(card => {
                const canBuy = card.price <= currentMoney;
                const cardElement = createShopCardElement(card, canBuy);

                switch (card.type) {
                    case 'role':
                        document.getElementById('roleCards').appendChild(cardElement);
                        break;
                    case 'action':
                        document.getElementById('actionCards').appendChild(cardElement);
                        break;
                    case 'total_weapon':
                        document.getElementById('totalWeaponCards').appendChild(cardElement);
                        break;
                    case 'role_weapon':
                        document.getElementById('roleWeaponCards').appendChild(cardElement);
                        break;
                }
            });

            // 恢复滑动条的位置
            Array.from(document.getElementsByClassName('card-scroll-container')).forEach(container => {
                container.scrollLeft = scrollPositions[container.id];
            });
        })
        .catch(error => console.error('获取卡牌列表失败:', error));
}

// 创建卡牌元素
function createShopCardElement(card, canBuy) {
    const cardDiv = document.createElement('div');
    cardDiv.className = `card ${canBuy ? '' : 'disabled'}`;

    // 根据卡牌类型生成不同的属性显示
    let statsHTML = '';
    switch (card.type) {
        case 'role':
            statsHTML = `
            <div class="stat"><span>生命值：</span><span>${card.hp}</span></div>
            <div class="stat"><span>攻击力：</span><span>${card.attack}</span></div>
        `;
            break;
        case 'action':
            statsHTML = `
            ${card.addSelfHP ? `<div class="stat"><span>回血：</span><span>+${card.addSelfHP}</span></div>` : ''}
            ${card.addSelfMP ? `<div class="stat"><span>回蓝：</span><span>+${card.addSelfMP}</span></div>` : ''}
            ${card.addSelfMPMAX ? `<div class="stat"><span>增加法力上限：</span><span>+${card.addSelfMPMAX}</span></div>` : ''}
            ${card.addEnemyHP ? `<div class="stat"><span>对敌方伤害：</span><span>${card.addEnemyHP}</span></div>` : ''}
            ${card.addEnemyMP ? `<div class="stat"><span>减少敌方蓝量：</span><span>${card.addEnemyMP}</span></div>` : ''}
            ${card.cost ? `<div class="stat"><span>技能消耗：</span><span>${card.cost}</span></div>` : ''}
        `;
            break;
        case 'total_weapon':
            statsHTML = `
            ${card.addHPMax ? `<div class="stat"><span>增加生命上限：</span><span>+${card.addHPMax}</span></div>` : ''}
        `;
            break;
        case 'role_weapon':
            statsHTML = `
            ${card.addHPMax ? `<div class="stat"><span>增加生命上限：</span><span>+${card.addHPMax}</span></div>` : ''}
            ${card.addAttack ? `<div class="stat"><span>增加攻击力：</span><span>+${card.addAttack}</span></div>` : ''}
        `;
            break;
    }

    cardDiv.innerHTML = `
    <img class="card-image" src="${card.imageUrl || 'https://via.placeholder.com/240x160?text=卡牌立绘'}" alt="${card.name}">
    <div class="card-content">
        <div class="card-name">${card.name}</div>
        <div class="card-description">${card.introduction}</div>
        <div class="card-stats">
            ${statsHTML}
        </div>
        <div class="price-container">
            <span>价格：</span>
            <span class="price ${canBuy ? '' : 'insufficient'}">${card.price} 金币</span>
        </div>
        <button class="buy-button"
                onclick="purchaseCard(${card.id})"
                ${canBuy ? '' : 'disabled'}>
            购买
        </button>
    </div>
`;

    return cardDiv;
}

// 购买卡牌
function purchaseCard(cardId) {
    if (confirm('确定要购买这张卡牌吗？')) {
        fetch('/api/shop/purchase-card', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ cardId: cardId })
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('购买成功！');
                    // 刷新金钱和卡牌列表
                    fetchMoney();
                    fetchAllCards();
                } else {
                    alert('购买失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('购买失败:', error);
                alert('购买失败，请稍后重试');
            });
    }
}